﻿using System;
using System.Text;
using System.Web.UI;
using System.Xml.Linq;

namespace SPAdaptiveMenu.Controls
{
    /// <summary>
    /// CheckBox menu item
    /// </summary>
    public class MenuCheck : MenuOption
    {
        /// <summary>
        /// Checked flag
        /// </summary>
        public bool Checked { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public MenuCheck()
        {
            Checked = false;
        }

        protected override object SaveControlState()
        {
            base.SaveControlState();
            var obj = base.SaveControlState();
            return obj != null
                ? (object)new Pair(obj, Serialized.ToString())
                : Serialized.ToString();
        }

        protected override void LoadControlState(object state)
        {
            if (state == null) return;
            var p = state as Pair;
            if (p != null)
            {
                base.LoadControlState(p.First);
                InitProperties(XElement.Parse((string)p.Second));
            }
            else
            {
                if (state is string)
                    InitProperties(XElement.Parse((string)state));
                else
                    base.LoadControlState(state);
            }
        }

        protected internal override void InitProperties(XElement element)
        {
            if (element == null) return;
            base.InitProperties(element);
            Checked = element.Attribute("Checked").Value.Equals("TRUE", StringComparison.InvariantCultureIgnoreCase);
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (Page.IsPostBack)
            {
                var target = Page.Request.Form["__EVENTTARGET"];
                if (target == UniqueID)
                {
                    var flag = Page.Request.Form["__EVENTARGUMENT"] == "1";
                    Checked = flag;
                    var arg = new MenuCheckEventArgs { Flag = Page.Request.Form["__EVENTARGUMENT"] == "1", Item = this };
                    OnClick(arg);
                }

            }
        }

        protected override void Render(HtmlTextWriter writer)
        {
            var sb = new StringBuilder();
            var onclick = Page.ClientScript.GetPostBackEventReference(this, Checked ? "0" : "1");
            sb.AppendFormat(@"<ie:menuitem id=""{0}"" type=""option""", ClientID);
            sb.AppendFormat(@" onMenuClick=""{0}""", onclick);
            if (!string.IsNullOrEmpty(Title))
                sb.AppendFormat(@" title=""{0}""", Title);
            if (!string.IsNullOrEmpty(Description))
                sb.AppendFormat(@" description=""{0}""", Description);
            if (!string.IsNullOrEmpty(Title))
                sb.AppendFormat(@" text=""{0}""", Title);
            if (Disabled)
                sb.Append(@" enabled=""false""");
            sb.Append(@" checked=""" + (Checked ? "true" : "false") + @"""");
            if (Hidden)
                sb.Append(@" hidden=""true""");
            sb.Append("></ie:menuitem>");
            writer.Write(sb.ToString());
        }

        ///<summary>
        ///</summary>
        ///<param name="eventArgument"></param>
        public void RaisePostBackEvent(string eventArgument)
        {
            var e = new MenuCheckEventArgs() { Flag = eventArgument == "1", Item = this };
            OnClick(e);
        }

        ///<summary>
        ///</summary>
        public event EventHandler Click
        {
            add { _click += value; }
            remove { _click -= value; }
        }

        protected virtual void OnClick(MenuCheckEventArgs e)
        {
            if (_click != null)
                _click(this, e);
        }

        private EventHandler _click;

        protected internal override XElement Serialized
        {
            get
            {
                var element = base.Serialized;
                element.Attribute("Type").Value = ItemType.ToString();
                element.Add(new XAttribute("Checked", Checked));
                return element;
            }
        }

        protected internal override XElement HTML
        {
            get
            {
                var element = base.HTML;
                var onclick = Serialized.Attribute("OnClickText").Value;
                element.Attribute("onMenuClick").Value = onclick;
                element.Add(new XAttribute("checked", Checked));
                return element;
            }
        }
    }
}
